package com.gitee.smsdistribution.intercepter;

import com.gitee.smsdistribution.common_response.exception.UnAuthorizedException;
import com.gitee.smsdistribution.model.User;
import com.gitee.smsdistribution.util.Constant;
import com.gitee.smsdistribution.util.CookiesUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

@Slf4j
@Component
public class AuthInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 鉴权除login外的所有请求
        if (request.getRequestURI().contains(Constant.LOGIN)) {
            return true;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            throw new UnAuthorizedException("Cookie is empty, please login first", null);
        }

        Cookie userIdCookie = CookiesUtil.getCookieByName(request, Constant.ID);
        if (Objects.isNull(userIdCookie)) {
            throw new UnAuthorizedException("Cookie can not find id, please login first", null);
        }
        Cookie userNameCookie = CookiesUtil.getCookieByName(request, Constant.ID);
        if (Objects.isNull(userNameCookie)) {
            throw new UnAuthorizedException("Cookie can not find name, please login first", null);
        }

        Long userId = Long.valueOf(userIdCookie.getValue());
        String userName = userNameCookie.getValue();
        RequestContext.setUserHolder(User.builder().id(userId).name(userName).build());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestContext.remove();
    }
}
